package p1;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: LianBao
 * Date: 2024-09-15
 * Time: 10:29
 */


class ListNode {
    int val;
    ListNode next;

    ListNode() {
    }

    ListNode(int val) {
        this.val = val;
    }

    ListNode(int val, ListNode next) {
        this.val = val;
        this.next = next;
    }
}


public class demo {

    //1.给你一个链表的头节点 head 和一个整数 val ，请你删除链表中所有满足 Node.val == val 的节点，并返回 新的头节点
    public ListNode removeElements1(ListNode head, int val) {
        if (head == null) {
            return null;
        }

        //处理前面部分
        while (head.val == val) {
            head = head.next;
            if (head == null) {
                return null;
            }
        }
        ListNode cur = head;
        ListNode cP = null;

        while (cur != null) {
            cP = cur;
            if (cur.val == val) {
                cP.next = cur.next;
            }
            cur = cur.next;
        }
        return head;
    }

    public ListNode removeElements(ListNode head, int val) {
        if (head == null) {
            return null;
        }
        // 处理前面部分
        while (head.val == val) {
            head = head.next;
            if (head == null) {
                return head;
            }
        }
        ListNode prev = head;
        ListNode cur = head.next;//处理完前部分,所以head的值一定不是val,所以让cur=head.next
        while (cur != null) {
            if (cur.val == val) {
                prev.next = cur.next;
            } else {
                prev = cur;
            }
            cur = cur.next;
        }
        return head;
    }
}
